package com.mzj.saas.jobs.report.service;

import com.mzj.saas.jobs.EnterpriseData.entity.DepartmentHierarchy;
import com.mzj.saas.jobs.EnterpriseData.repository.DepartmentHierarchyRepository;
import com.mzj.saas.jobs.commons.DateUtils;
import com.mzj.saas.jobs.report.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.jobs.report.repository.DepartmentEnterpriseTagRefRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 投诉建议统计
 */
@Service
public class ReportComplainStatisticsService {

    private static Logger log = LoggerFactory.getLogger(ReportComplainStatisticsService.class);

    private static Map<String,Object> dateMap = new HashMap<>();

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;

    public String work() throws Exception {

        List<DepartmentHierarchy> departmentHierarchyList = departmentHierarchyRepository.findAll();
        //物业公司集合
        List<DepartmentHierarchy> propertyList = new ArrayList<>();
        for (DepartmentHierarchy dh : departmentHierarchyList) {
            List<DepartmentEnterpriseTagRef> entityList = departmentEnterpriseTagRefRepository.findByDepRefId(dh.getId());
            List<Long> tagIdList = entityList.stream().map(DepartmentEnterpriseTagRef::getTagId).collect(Collectors.toList());
            if (tagIdList.contains(4L)) {    //物业公司
                propertyList.add(dh);
            }
        }

        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String lDate = formatter.format(date);

        List<String> datas = new ArrayList<>();

        SimpleDateFormat df = new SimpleDateFormat("HH");
        String str = df.format(date);
        int hh = Integer.parseInt(str);
        if (hh >= 0 && hh <= 6) {
            //判断到凌晨只统计一次昨天数据
            Date day = DateUtils.getYesterday(new Date());
            String yesterday = formatter.format(day);
            if(!dateMap.containsKey(yesterday)) {
                dateMap.clear();
                dateMap.put(yesterday, yesterday);
                datas.add(yesterday);
            }
        }
        datas.add(lDate);

        for(String localDate : datas) {
            log.info("ReportComplainStatisticsService 投诉建议统计  start  date={}",localDate);

            String deleteMxSQL =" delete from saas_report_complain_statistics where stat_date=  " +localDate;
            //删除当前统计时间记录
            jdbcTemplate.execute(deleteMxSQL);

            for(DepartmentHierarchy hierarchy : propertyList) {

                //查询  投诉建议  当天记录
                String complainSuggestSQL = " SELECT r.status,r.type,count(1) AS num FROM saas_complain_suggest r " +
                        "       WHERE 1=1 AND r.org_id = " + hierarchy.getOrgId() + " AND DATE_FORMAT(r.create_time,'%Y%m%d')=  " + localDate +
                        "       GROUP BY r.status,r.type  ";

                List<Map<String, Object>> complainSuggestList = jdbcTemplate.queryForList(complainSuggestSQL);

                List<Map<String, Object>> resultList = new ArrayList<>();

                for (int i = 1; i <= 2; i++) {
                    Map<String, Object> result = new HashMap<>();
                    result.put("type", i);   //状态类型：1待处理  2已处理

                    for (Map<String, Object> map : complainSuggestList) {

                        if (Integer.parseInt(map.get("status").toString()) == ( Integer.parseInt(result.get("type").toString())-1 ) ) {
                            if (Integer.parseInt(map.get("type").toString()) == 1) {    //投诉类型 1投诉 2建议
                                result.put("complain_number", map.get("num"));  //1投诉
                            } else {
                                result.put("suggest_number", map.get("num"));  //2建议
                            }
                        }


                    }

                    resultList.add(result);
                }

                //数据插入   saas_report_complain_statistics

                String insertSql = " INSERT INTO saas_report_complain_statistics(stat_date,type,complain_number,suggest_number,house_property_id)  " +
                        "  VALUE(?,?,?,?,?) ";

                jdbcTemplate.batchUpdate(insertSql, resultList, resultList.size(), (ps, argument) -> {
                    ps.setString(1, localDate);
                    ps.setInt(2, Integer.parseInt(argument.get("type").toString()));
                    ps.setInt(3, argument.get("complain_number") != null ? Integer.parseInt(argument.get("complain_number").toString()) : 0);
                    ps.setInt(4, argument.get("suggest_number") != null ? Integer.parseInt(argument.get("suggest_number").toString()) : 0);
                    ps.setLong(5, hierarchy.getOrgId());

                });

            }
            log.info("ReportComplainStatisticsService 投诉建议统计  end");
        }

        return "SUCCESS";

    }


}
